import axios from 'axios'
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
const baseUrl = 'http://123.57.67.13:8082/'
const http = axios.create({
  baseURL:baseUrl,
  timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // 处理错误响应
    if (error.response.status === 401) {
      const navigate = useNavigate();
      message.error('登录已过期，请重新登录');
      localStorage.removeItem('token');
      navigate('/login');
    }
    return Promise.reject(error)
  }
)

export default http